package com.atguigu.web;

import com.atguigu.Bean.C_user;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {

    private UserService us=new UserServiceImpl();

    /**
     * 登录操作
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //登录操作
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        C_user c =new C_user();
        Map<String, String[]> map = req.getParameterMap();
        WebUtils.copyParamToBean(map,c);
        /**
         * 直接调用该方法
         */
        C_user loginUser = us.login(c);
        if(loginUser==null){
            //返回登陆页面
            System.out.println("用户名或密码错误");
            req.setAttribute("Error","用户名或密码错误!");
            req.getRequestDispatcher("/pages/UserPages/login.jsp").forward(req,resp);
        }else {
            //跳转到登录成功之后的页面
            System.out.println("登录成功");
//            req.setAttribute("name",username);
            Cookie cookie=new Cookie("username",username);//把username放在cookie中
            cookie.setMaxAge(10800);//设置存活时间为3h
            resp.addCookie(cookie);
            req.getSession().setAttribute("user",loginUser);
            req.setAttribute("Error",null);
            req.getRequestDispatcher("/pages/UserPages/index.jsp").forward(req,resp);

        }
    }

    /**
     * 注册操作
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //注册操作
        //1、获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String user_ID = req.getParameter("user_ID");
        String email = req.getParameter("email");
        String realname = req.getParameter("realname");
        String sex = req.getParameter("sex");
        C_user c =new C_user();
        Map<String, String[]> map = req.getParameterMap();
        WebUtils.copyParamToBean(map,c);
        //1.2、获取服务器session中的验证码的值
        String serverCode = (String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //1.3、删除服务器session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //1.5、获取客户端发过来的验证码
        String userCode = (String) req.getParameter("userCode");
        /**
         * 直接调用该方法
         */
        //2、检查验证码是否正确
        if(serverCode!=null&&serverCode.equals(userCode)==true){
            //3、检查用户名是否可用
            if(us.existsUsername(username)==true){
                //用户名已被占用
                //控制台提示并且回复页面初始状态
                req.setAttribute("Error","用户名已被占用!");
                System.out.println("用户名已被占用");
                req.getRequestDispatcher("/pages/UserPages/register.jsp").forward(req,resp);
                //斜杠        代表“http://ip:port/工程路径/”
            }
            else{//可用,保存数据
                us.registUser(c);
//                req.getRequestDispatcher("/pages/UserPages/login.jsp").forward(req,resp);
                resp.sendRedirect(req.getContextPath()+"/pages/UserPages/login.jsp");
                /**这里运用请求重定向可以利用其两次请求的特点
                 * 可以避免因刷新引起表单重复提交而引起的重复注册出错问题
                 */
            }
        }else{//验证码错误
            //控制台提示并且回复页面初始状态
            req.setAttribute("Error","验证码错误!");
            System.out.println("验证码错误");
            req.getRequestDispatcher("/pages/UserPages/register.jsp").forward(req,resp);
        }
    }

    /**
     * 注销操作
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、销毁session中用户的信息(或者销毁session)
        req.getSession().invalidate();//直接销毁
        //2、重定向到首页(或登陆页面)
        resp.sendRedirect(req.getContextPath());
    }
    /*
    注册时，使用ajax验证用户名是否可用
     */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取请求的参数username
        String username = req.getParameter("username");
        //2、调用UserService。existsUsername()判断用户名是否可用
        boolean b = us.existsUsername(username);
        //3、判断重名就将判断结果写入map里，将map转换为json传回客户端
        //由客户端判断是否重名
        Map<String,Object> respResult=new Hashtable<>();
        respResult.put("existsUsername",b);
        Gson gson=new Gson();
        String toJson = gson.toJson(respResult);
        resp.getWriter().write(toJson);
    }
}
